package com.example.question.tree.tree2;

import com.example.question.tree.tree1.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Date 2023-07-12
 * @Author Jonathan
 */
public class Code09_437 {

    // todo  还可以前缀和优化

    public int pathSum(TreeNode root, int targetSum) {
        return dfs(root, new ArrayList<>(), targetSum);
    }

    public int dfs(TreeNode node, List<Long> parentSum, int targetSum) {
        if (node == null) {
            return 0;
        }
        int cnt = 0;
        List<Long> currentSum = new ArrayList<>();
        for (Long integer : parentSum) {
            long val = integer + node.val;
            currentSum.add(val);
            if (targetSum == val) {
                cnt++;
            }
        }
        currentSum.add((long) node.val);
        if (node.val == targetSum) {
            cnt++;
        }
        int left = dfs(node.left, currentSum, targetSum);
        int right = dfs(node.right, currentSum, targetSum);
        return left + cnt + right;
    }
}
